<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">

      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.device_delete"
                   @click="handleDelete">删 除
        </el-button>

        <el-button size="small" type="primary" @click="handleExcel">下载模版</el-button>

        <el-upload :show-file-list="showFileList" action="/blade-lamp/device/import" :limit="1" :on-change="handleChange" :before-upload="beforeHandler" :multiple="multiple" class="device-upload">
          <el-button size="small" type="primary">导入</el-button>
        </el-upload>

      </template>

      <template slot-scope="scope" slot="menuBtn">

      </template>

      <template slot-scope="{row}"
                slot="type">
        <el-tag>{{row.typeName}}</el-tag>
      </template>

      <template slot-scope="{row}"
                slot="currentControllerStatus">
        <el-tag>{{row.statusName}}</el-tag>
      </template>

      <!--<template slot-scope="{row}"
                slot="roadSection">
        <el-tag>{{row.roadSectionName}}</el-tag>
      </template>-->

    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, importDevice} from "@/api/lamp/device";
  //import {getAreaTree} from "@/api/lamp/area";
  import {getToken} from '@/util/auth';
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        showFileList: false,
        multiple: false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 350,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          labelWidth: 120,
          menuType:'menu',
          menuWidth: 120,
          column: [
            {
              label: "设备编码",
              minWidth:110,
              search: true,
              prop: "sn",
              rules: [{
                required: true,
                message: "请输入设备编码",
                trigger: "blur"
              }]
            },
            {
              label: "网关IMEI",
              prop: "imei",
                minWidth:130,
              rules: [{
                required: false,
                message: "请输入网关IMEI",
                trigger: "blur"
              }]
            },
            {
              label: "IOT平台ID",
              prop: "deviceId",
              addDisplay: false,
              editDisplay: false,
              minWidth:180,
              rules: [{
                required: false,
                message: "请输入iot平台设备id",
                trigger: "blur"
              }]
            },
            {
              label: "设备名称",
              prop: "name",
              rules: [{
                required: true,
                message: "请输入设备名称",
                trigger: "blur"
              }]
            },
            {
              label: "设备类型",
              prop: "type",
              minWidth:105,
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=device_type",
              props: {
                  label: "dictValue",
                  value: "dictKey"
              },
              slot: true,
              search: true,
              rules: [{
                required: true,
                message: "请输入设备类型",
                trigger: "blur"
              }]
            },
            {
              label: "二维码",
              prop: "qrcode",
              minWidth:110,
              rules: [{
                required: true,
                message: "请输入二维码",
                trigger: "blur"
              }]
            },
            {
              label: "供应商",
              prop: "supplierSn",
                type: "select",
                dicUrl: "/api/blade-lamp/supplier/select",
                //slot: true,
                minWidth: 110,
                props: {
                    label: "name",
                    value: "supplierSn"
                },
              rules: [{
                required: false,
                message: "请选择供应商",
                trigger: "blur"
              }]
            },
            {
              label: "协议类型",
              prop: "protrolType",
              rules: [{
                required: false,
                message: "请输入协议类型",
                trigger: "blur"
              }]
            },
            {
              label: "网络协议类型",
              prop: "netProtrolType",
              minWidth:110,
              rules: [{
                required: false,
                message: "请输入网络协议类型",
                trigger: "blur"
              }]
            },
              {
                  label: "电信编码",
                  prop: "telecomCode",
                  addDisplay: false,
                  editDisplay: false,
                  rules: [{
                      required: true,
                      message: "请输入电信编码",
                      trigger: "blur"
                  }]
              },
            /*{
              label: "路段[街道]",
              prop: "roadSection",
              type: "tree",
              dicUrl: "/api/blade-lamp/area/tree",
              slot: true,
              minWidth: 110,
              props: {
                label: "title",
                value: "value"
              },
              rules: [{
                required: true,
                message: "请选择路段[街道]",
                trigger: "click"
              }]
            },
            {
              label: "路灯编号",
              prop: "lampNumber",
              rules: [{
                required: true,
                message: "请输入路灯编号",
                trigger: "blur"
              }]
            },
            {
              label: "安装经度",
              prop: "longitude",
                minWidth:100,
              rules: [{
                required: true,
                message: "请输入安装经度",
                trigger: "blur"
              }]
            },
            {
              label: "安装纬度",
              prop: "latitude",
                minWidth:100,
              rules: [{
                required: true,
                message: "请输入安装纬度",
                trigger: "blur"
              }]
            },*/
            {
              label: "控制器状态",
              prop: "currentControllerStatus",
              addDisplay: false,
              editDisplay: false,
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=controller_status",
              minWidth:100,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              slot: true,
              search: true,
              searchLabelWidth: 100,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    watch: {

    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.device_add, false),
          viewBtn: this.vaildData(this.permission.device_view, false),
          delBtn: this.vaildData(this.permission.device_delete, false),
          editBtn: this.vaildData(this.permission.device_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, loading, done) {
        add(row).then(() => {
          loading();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          done();
          console.log(error);
        });
      },
      rowUpdate(row, index, loading, done) {
        update(row).then(() => {
          loading();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          done();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      beforeHandler(file, fileList) {
        // FormData 对象
        const form = new FormData();
        // 文件对象
        form.append('file', file);
        this.uploadHandler(form); // 调用自定义的上传
        return false; // 阻止组件本身的上传
      },
      uploadHandler(data){
        importDevice(data).then(res => {
          if (res.status === 200 && res.statusText === 'OK') {
            if (res.data && res.data.success === true) {
              this.onLoad(this.page, this.query);
            } else {
              this.$message(res.data.msg);
            }
          } else {
            this.$message('status' + res.status+'; text:'+res.statusText);
          }
        });
      },
        handleChange(file, fileLis) {

        },
        handleExcel() {
          window.open('/api/blade-lamp/device/import/template?Blade-Auth='+'bearer ' + getToken());
        },
    }
  };
</script>

<style scoped>
  .device-upload {
    display: inline-block;
  }
</style>
